package com.eshop.print;

import com.eshop.utils.RedisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.config.RequestConfig;
import com.eshop.utils.DateUtils;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import java.util.ArrayList;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.io.FileOutputStream;
import java.util.Date;
import java.text.SimpleDateFormat;

public class PrintUtil4
{
    public static final String URL = "http://api.feieyun.cn/Api/Open/";
    public static final String USER;
    public static final String UKEY;
    public static final String SN = "918502791";
    
    public void writeFile(final String path, String content) {
        content = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date()) + ",保存的订单日志信息为: " + content;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path, true);
            fos.write(content.getBytes());
            fos.write("\r<BR>".getBytes());
        }
        catch (IOException e) {
            e.printStackTrace();
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                }
                catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                }
                catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }
    }
    
    public static void main(final String[] args) {
        try {
            System.out.println(new String(addPrintEquip("918502791", "nvz8kw5n", "测试", "").getBytes("ISO-8859-1"), "UTF-8"));
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    
    public static String addPrintEquip(final String sn, final String key, final String remark, final String phone) {
        final String printerContent = sn + " # " + key + " # " + remark + " # " + phone;
        final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add((NameValuePair)new BasicNameValuePair("user", PrintUtil4.USER));
        final String STIME = String.valueOf(System.currentTimeMillis() / 1000L);
        nvps.add((NameValuePair)new BasicNameValuePair("stime", STIME));
        nvps.add((NameValuePair)new BasicNameValuePair("sig", signature(PrintUtil4.USER, PrintUtil4.UKEY, STIME)));
        nvps.add((NameValuePair)new BasicNameValuePair("apiname", "Open_printerAddlist"));
        nvps.add((NameValuePair)new BasicNameValuePair("printerContent", printerContent));
        return sendHttpRequest(nvps);
    }
    
    public static String editPrintEquip(final String sn, final String remark, final String phone) {
        final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add((NameValuePair)new BasicNameValuePair("user", PrintUtil4.USER));
        final String STIME = String.valueOf(System.currentTimeMillis() / 1000L);
        nvps.add((NameValuePair)new BasicNameValuePair("stime", STIME));
        nvps.add((NameValuePair)new BasicNameValuePair("sig", signature(PrintUtil4.USER, PrintUtil4.UKEY, STIME)));
        nvps.add((NameValuePair)new BasicNameValuePair("apiname", "Open_printerEdit"));
        nvps.add((NameValuePair)new BasicNameValuePair("sn", sn));
        nvps.add((NameValuePair)new BasicNameValuePair("name", remark));
        nvps.add((NameValuePair)new BasicNameValuePair("phonenum", phone));
        return sendHttpRequest(nvps);
    }
    
    public static String printOrder(final String sn, final String contentTitle, final List<OrderPrint> orderList, final PrintOrderDataVO order, final int lian) {
        final String content = getPrintContent(contentTitle, orderList, 14, 6, 3, 6, order, lian + 1);
        return print(sn, content);
    }
    
    public static String printOrderByAdvance(final List<OrderPrint> orderList, final String title, final String mobile, final String name, final String payPrice) {
        final String content = getOrderByAdvance(orderList, 14, 6, 3, 6, title, mobile, name, payPrice);
        return print("918502791", content);
    }
    
    public static String printContentByStore(final String contentTitle, final List<OrderPrint> orderList, final int b1, final int b3, final PrintStoreOrderVO printStoreOrder, final int lian) {
        final String content = getPrintContentByStore(contentTitle, orderList, b1, b3, printStoreOrder, lian + 1);
        return print(printStoreOrder.getDriverNo(), content);
    }
    
    public static String print(final String sn, final String content) {
        final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add((NameValuePair)new BasicNameValuePair("user", PrintUtil4.USER));
        final String STIME = String.valueOf(System.currentTimeMillis() / 1000L);
        nvps.add((NameValuePair)new BasicNameValuePair("stime", STIME));
        nvps.add((NameValuePair)new BasicNameValuePair("sig", signature(PrintUtil4.USER, PrintUtil4.UKEY, STIME)));
        nvps.add((NameValuePair)new BasicNameValuePair("apiname", "Open_printMsg"));
        nvps.add((NameValuePair)new BasicNameValuePair("sn", sn));
        nvps.add((NameValuePair)new BasicNameValuePair("content", content));
        nvps.add((NameValuePair)new BasicNameValuePair("times", "1"));
        return sendHttpRequest(nvps);
    }
    
    public static String getOrderByAdvance(final List<OrderPrint> orderList, final int b1, final int b2, final int b3, final int b4, final String headTitle, final String mobile, final String name, final String payPrice) {
        String orderInfo = "<CB>" + headTitle + "</CB><BR>";
        orderInfo += "名称           单价  数量 金额<BR>";
        orderInfo += "--------------------------------<BR>";
        double totals = 0.0;
        for (int i = 0; i < orderList.size(); ++i) {
            String title = orderList.get(i).getTitle();
            String price = orderList.get(i).getPrice();
            String num = orderList.get(i).getNum();
            String total = "" + Double.valueOf(price) * Integer.parseInt(num);
            totals += Double.parseDouble(total);
            price = addSpace(price, b2);
            num = addSpace(num, b3);
            total = addSpace(total, b4);
            final String otherStr = " " + price + num + " " + total;
            int tl = 0;
            try {
                tl = title.getBytes("GBK").length;
            }
            catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            final int spaceNum = (tl / b1 + 1) * b1 - tl;
            if (tl < b1) {
                for (int k = 0; k < spaceNum; ++k) {
                    title += " ";
                }
                title += otherStr;
            }
            else if (tl == b1) {
                title += otherStr;
            }
            else {
                List<String> list = null;
                if (isEn(title)) {
                    list = getStrList(title, b1);
                }
                else {
                    list = getStrList(title, b1 / 2);
                }
                final String s0 = titleAddSpace(list.get(0));
                title = s0 + otherStr + "<BR>";
                String s2 = "";
                for (int j = 1; j < list.size(); ++j) {
                    s2 += list.get(j);
                }
                try {
                    s2 = getStringByEnter(b1, s2);
                }
                catch (Exception e2) {
                    e2.printStackTrace();
                }
                title += s2;
            }
            orderInfo = orderInfo + title + "<BR>";
        }
        orderInfo += "--------------------------------<BR>";
        orderInfo = orderInfo + "合计：" + totals + "元<BR>";
        orderInfo = orderInfo + "实付：" + payPrice + "元<BR>";
        orderInfo = orderInfo + "联系人：" + name + "<BR>";
        orderInfo = orderInfo + "联系电话：" + mobile + "<BR>";
        orderInfo = orderInfo + "下单时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "<BR>";
        return orderInfo;
    }
    
    public static String getPrintContentByStore(final String contentTitle, final List<OrderPrint> orderList, final int b1, final int b3, final PrintStoreOrderVO printStoreOrder, final int lian) {
        String orderInfo = "<CB>----第" + lian + "联----</CB><BR>";
        orderInfo = orderInfo + "<CB>" + contentTitle + "</CB><BR>";
        orderInfo += "名称                      数量<BR>";
        orderInfo += "--------------------------------<BR>";
        for (int i = 0; i < orderList.size(); ++i) {
            String title = orderList.get(i).getTitle();
            String num = orderList.get(i).getNum();
            num = addSpace(num, b3);
            final String otherStr = "  " + num;
            int tl = 0;
            try {
                tl = title.getBytes("GBK").length;
            }
            catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            final int spaceNum = (tl / b1 + 1) * b1 - tl;
            if (tl < b1) {
                for (int k = 0; k < spaceNum; ++k) {
                    title += " ";
                }
                title += otherStr;
            }
            else if (tl == b1) {
                title += otherStr;
            }
            else {
                List<String> list = null;
                if (isEn(title)) {
                    list = getStrList(title, b1);
                }
                else {
                    list = getStrList(title, b1 / 2);
                }
                final String s0 = titleAddSpace(list.get(0));
                title = s0 + otherStr + "<BR>";
                String s2 = "";
                for (int j = 1; j < list.size(); ++j) {
                    s2 += list.get(j);
                }
                try {
                    s2 = getStringByEnter(b1, s2);
                }
                catch (Exception e2) {
                    e2.printStackTrace();
                }
                title += s2;
            }
            orderInfo = orderInfo + title + "<BR>";
        }
        orderInfo += "--------------------------------<BR>";
        orderInfo = orderInfo + "社区门店：" + contentTitle + "<BR>";
        orderInfo = orderInfo + "开始时间：" + printStoreOrder.getStartTime() + "<BR>";
        orderInfo = orderInfo + "截止时间：" + printStoreOrder.getEndTime() + "<BR>";
        orderInfo = orderInfo + "打印时间：" + DateUtils.getTime() + "<BR>";
        return orderInfo;
    }
    
    public static String getPrintContent(final String contentTitle, final List<OrderPrint> orderList, final int b1, final int b2, final int b3, final int b4, final PrintOrderDataVO order, final int lian) {
        String orderInfo = "<CB>----第" + lian + "联----</CB><BR>";
        orderInfo = orderInfo + "<CB>" + contentTitle + "</CB><BR>";
        orderInfo += "名称           单价  数量 金额<BR>";
        orderInfo += "--------------------------------<BR>";
        double totals = 0.0;
        for (int i = 0; i < orderList.size(); ++i) {
            String title = orderList.get(i).getTitle();
            String price = orderList.get(i).getPrice();
            String num = orderList.get(i).getNum();
            String total = "" + Double.valueOf(price) * Integer.parseInt(num);
            totals += Double.parseDouble(total);
            price = addSpace(price, b2);
            num = addSpace(num, b3);
            total = addSpace(total, b4);
            final String otherStr = " " + price + num + " " + total;
            int tl = 0;
            try {
                tl = title.getBytes("GBK").length;
            }
            catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            final int spaceNum = (tl / b1 + 1) * b1 - tl;
            if (tl < b1) {
                for (int k = 0; k < spaceNum; ++k) {
                    title += " ";
                }
                title += otherStr;
            }
            else if (tl == b1) {
                title += otherStr;
            }
            else {
                List<String> list = null;
                if (isEn(title)) {
                    list = getStrList(title, b1);
                }
                else {
                    list = getStrList(title, b1 / 2);
                }
                final String s0 = titleAddSpace(list.get(0));
                title = s0 + otherStr + "<BR>";
                String s2 = "";
                for (int j = 1; j < list.size(); ++j) {
                    s2 += list.get(j);
                }
                try {
                    s2 = getStringByEnter(b1, s2);
                }
                catch (Exception e2) {
                    e2.printStackTrace();
                }
                title += s2;
            }
            orderInfo = orderInfo + title + "<BR>";
        }
        orderInfo += "--------------------------------<BR>";
        orderInfo = orderInfo + "社区门店：" + order.getStoreName() + "<BR>";
        orderInfo = orderInfo + "订单编号：" + order.getOrderId() + "<BR>";
        orderInfo = orderInfo + "合计：" + totals + "元<BR>";
        orderInfo = orderInfo + "实付：" + order.getPayPrice() + "元<BR>";
        orderInfo = orderInfo + "联系人：" + order.getRealName() + "<BR>";
        orderInfo = orderInfo + "详细地址：" + order.getUserAddress() + "<BR>";
        orderInfo = orderInfo + "联系电话：" + order.getUserPhone() + "<BR>";
        orderInfo = orderInfo + "下单时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "<BR>";
        orderInfo = orderInfo + "备注：" + order.getMark() + "<BR>";
        return orderInfo;
    }
    
    public static String sendHttpRequest(final List<NameValuePair> nvps) {
        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        final HttpPost post = new HttpPost("http://api.feieyun.cn/Api/Open/");
        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity((HttpEntity)new UrlEncodedFormEntity((List)nvps, "utf-8"));
            response = httpClient.execute((HttpUriRequest)post);
            final int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                final HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    result = EntityUtils.toString(httpentity);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            close(response, post, httpClient);
        }
        return result;
    }
    
    public static void close(final CloseableHttpResponse response, final HttpPost post, final CloseableHttpClient httpClient) {
        try {
            if (response != null) {
                response.close();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        try {
            post.abort();
        }
        catch (Exception e2) {
            e2.printStackTrace();
        }
        try {
            httpClient.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static String titleAddSpace(String str) {
        int k = 0;
        final int b = 14;
        try {
            k = str.getBytes("GBK").length;
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < b - k; ++i) {
            str += " ";
        }
        return str;
    }
    
    public static String getStringByEnter(final int length, final String string) throws Exception {
        for (int i = 1; i <= string.length(); ++i) {
            if (string.substring(0, i).getBytes("GBK").length > length) {
                return string.substring(0, i - 1) + "<BR>" + getStringByEnter(length, string.substring(i - 1));
            }
        }
        return string;
    }
    
    public static String addSpace(String str, final int size) {
        final int len = str.length();
        if (len < size) {
            for (int i = 0; i < size - len; ++i) {
                str += " ";
            }
        }
        return str;
    }
    
    public static Boolean isEn(final String str) {
        Boolean b = false;
        try {
            b = (str.getBytes("GBK").length == str.length());
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return b;
    }
    
    public static List<String> getStrList(final String inputString, final int length) {
        int size = inputString.length() / length;
        if (inputString.length() % length != 0) {
            ++size;
        }
        return getStrList(inputString, length, size);
    }
    
    public static List<String> getStrList(final String inputString, final int length, final int size) {
        final List<String> list = new ArrayList<String>();
        for (int index = 0; index < size; ++index) {
            final String childStr = substring(inputString, index * length, (index + 1) * length);
            list.add(childStr);
        }
        return list;
    }
    
    public static String substring(final String str, final int f, final int t) {
        if (f > str.length()) {
            return null;
        }
        if (t > str.length()) {
            return str.substring(f, str.length());
        }
        return str.substring(f, t);
    }
    
    private static String signature(final String USER, final String UKEY, final String STIME) {
        return DigestUtils.sha1Hex(USER + UKEY + STIME);
    }
    
    static {
        USER = RedisUtil.get("fei_e_user");
        UKEY = RedisUtil.get("fei_e_ukey");
    }
}
